/**
 * gcog - generate code with inlined Groovy code.
 * http://code.google.com/p/gcog/
 * 
 * Copyright 2008, Tobias Hientzsch.
 * 
 * MIT license http://www.opensource.org/licenses/mit-license.php
 * 
 * Original idea and code from Cog code generation tool.
 * http://nedbatchelder.com/code/cog
 *
 * Copyright 2004-2008, Ned Batchelder.
 * 
 */

public class WhiteUtils{


	static def String whitePrefix(def strings) {
	    """ Determine the whitespace prefix common to all non-blank lines
	        in the argument list.
	    """
	    def prefix = ""
	    // Remove all blank lines from the list
	    strings = strings.grep { s-> s.trim() != ''}
	    if(!strings)
	    	return ''

	    // Find initial whitespace chunk in the first line.
	    // This is the best prefix we can hope for.
	    prefix = (strings[0] =~ /\s*/)[0]
	    
	    // Loop over the other strings, keeping only as much of
	    // the prefix as matches each string.
	    strings.each { s ->
	    	for(int i =0; i<prefix.length();i++) {
	    		if(prefix[i] != s[i]) {
	    			prefix = prefix[0..i-1]
	    		}
	    	}
	    }
	    return prefix
	}

	static def reindentBlock(def lines, newIndent='') {
	    """ Take a block of text as a string or list of lines.
	        Remove any common whitespace indentation.
	        Re-indent using newIndent, and return it as a single string.
	    """
	    if(lines instanceof String) {
	        lines = lines.split('\n', -1)
	    }
	    def oldIndent = whitePrefix(lines)
	    def outLines = []
	    lines.each{ l->
	        if(oldIndent)
	            l = l.replaceFirst(oldIndent, '')
	        if(l && newIndent) 
	            l = newIndent + l
	        outLines << l
	    }
	    return outLines.join('\n')
	}
	
	static def commonPrefix(strings) {
	    """ Find the longest string that is a prefix of all the strings.
	    """
	    if(!strings)
	        return ''
	    def prefix = strings[0]
	    strings.each{ s->
	        if(s.length() < prefix.length()) 
	            prefix = prefix.substring(0, s.length())
	        if(!prefix)
	            return ''
	        for (int i = 0; i<prefix.length(); i++) {
	            if(prefix[i] != s[i]) {
	                prefix = prefix.substring(0, i)
	                break
	            }
	        }
	    }
	    return prefix
	}
}
